package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrderMapper;
import com.itheima.reggie.service.*;
import com.itheima.reggie.utils.BaseContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import sun.util.resources.LocaleData;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Orders> implements OrderService {

    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderDetailService orderDetailService;


    /**
     * 用户下单
     * 1.获取下单用户的Id
     * 2.查询下单 购物车中的商品
     * 3.查询用户地址
     * 4.组装订单明细
     * 5.组装订单
     * 6.清空购物车
     *
     * @param orders
     */
    @Override
    public void submit(Orders orders) {
        //1.获取下单用户的Id
        Long currentId = BaseContext.getCurrentId();

        //2.查询用户下单 购物车中的商品
        LambdaQueryWrapper<ShoppingCart> shopLqw = new LambdaQueryWrapper<>();
        shopLqw.eq(currentId != null, ShoppingCart::getUserId, currentId);

        //购物车中的商品
        List<ShoppingCart> shoppingCarts = shoppingCartService.list(shopLqw);

        //查询地址
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        //查询用户
        User user = userService.getById(currentId);

        //4.组装订单明细
        long number = IdWorker.getId();  //获取订单号  IdWorker工具类

        AtomicInteger amount = new AtomicInteger(0);

        List<OrderDetail> orderDetailList = shoppingCarts.stream().map((shoppingCartItem) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(shoppingCartItem.getName());                //名字
            orderDetail.setImage(shoppingCartItem.getImage());              //图片
            orderDetail.setOrderId(number);                                 //订单Id
            orderDetail.setDishId(shoppingCartItem.getDishId());            //菜品Id
            orderDetail.setSetmealId(shoppingCartItem.getSetmealId());      //套餐Id
            orderDetail.setDishFlavor(shoppingCartItem.getDishFlavor());    //菜品口味
            orderDetail.setNumber(shoppingCartItem.getNumber());            //数量
            orderDetail.setAmount(shoppingCartItem.getAmount());            //金额
            amount.addAndGet(shoppingCartItem.getAmount().multiply(
                    new BigDecimal(shoppingCartItem.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        //5.组装订单
        orders.setId(number);
        orders.setNumber(String.valueOf(number));                    //订单号
        orders.setStatus(2);                                         //状态
        orders.setUserId(user.getId());                              //用户ID
        orders.setOrderTime(LocalDateTime.now());                    //下单时间
        orders.setCheckoutTime(LocalDateTime.now());                 //结账时间
//        orders.setAddressBookId(addressBook.getId());                //地址Id
//        order.setPayMethod();                                     //结账方式
        orders.setAmount(new BigDecimal(amount.get()));              //实收金额
//        orders.setRemark(orders.getRemark());                        //备注
        orders.setPhone(addressBook.getPhone());                     //电话
        orders.setUserName(user.getName());                          //下单用户
        orders.setConsignee(addressBook.getConsignee());             //收货人
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())//地址
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));

        //添加到订单表
        this.save(orders);
        //添加到订单详情表
        orderDetailService.saveBatch(orderDetailList);

        //清空购物车
        shoppingCartService.remove(shopLqw);
    }
}